package cn.com.libertymutual.sp.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;

import cn.com.libertymutual.core.http.HttpAndHttpsUtil;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.security.encoder.Md5PwdEncoder;
import cn.com.libertymutual.core.util.BeanUtilExt;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.util.StringUtil;
import cn.com.libertymutual.core.util.enums.CoreServiceEnum;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.core.xml.XmlBinder;
import cn.com.libertymutual.sp.bean.TbSpApplicant;
import cn.com.libertymutual.sp.bean.TbSpOrder;
import cn.com.libertymutual.sp.bean.TbSpSaleLog;
import cn.com.libertymutual.sp.bean.TbSpScoreConfig;
import cn.com.libertymutual.sp.bean.TbSpScoreLogIn;
import cn.com.libertymutual.sp.bean.TbSpScoreLogOut;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.dao.ApplicantDao;
import cn.com.libertymutual.sp.dao.OrderDao;
import cn.com.libertymutual.sp.dao.ScoreConfigDao;
import cn.com.libertymutual.sp.dao.ScoreLogInDao;
import cn.com.libertymutual.sp.dao.SpSaleLogDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.CallBackRequestDto;
import cn.com.libertymutual.sp.dto.RequestPayDto;
import cn.com.libertymutual.sp.dto.TQueryPayInfoResponseDto;
import cn.com.libertymutual.sp.dto.TQueryPolicyRequstDto;
import cn.com.libertymutual.sp.dto.callback.Appnt;
import cn.com.libertymutual.sp.dto.callback.Insured;
import cn.com.libertymutual.sp.dto.callback.OrderInfo;
import cn.com.libertymutual.sp.dto.callback.Product;
import cn.com.libertymutual.sp.dto.epayment.Epayment;
import cn.com.libertymutual.sp.dto.queryplans.CrossSaleKind;
import cn.com.libertymutual.sp.service.api.ActivityService;
import cn.com.libertymutual.sp.service.api.InsureService;
import cn.com.libertymutual.sp.service.api.PayService;
import cn.com.libertymutual.sp.service.api.PolicyService;
import cn.com.libertymutual.sp.service.api.ScoreService;
import cn.com.libertymutual.sys.bean.SysServiceInfo;
import cn.com.libertymutual.sys.service.api.ISequenceService;
import cn.com.libertymutual.wx.common.MessageType;
import cn.com.libertymutual.wx.service.WeChatService;

@Service("PaySevice")
@RefreshScope // 刷新配置无需重启服务
public class PaySeviceImpl implements PayService {

	@Value("${app.interface.topayment.url}")
	private String paymentURL;
	@Value("${app.interface.payinfofind.url}")
	private String payInfoFind;
	@Value("${app.interface.redirect.url}")
	private String redirectUrl;
	@Resource
	private RedisUtils redisUtils;
	@Autowired
	private ScoreConfigDao scoreConfigDao;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private TbSysHotareaDao tbSysHotareaDao;
	@Autowired
	private ScoreLogInDao scoreLogInDao;
	@Value("${app.interface.frontsuccess.url}")
	private String frontSuccess;

	@Value("${app.interface.fronterror.url}")
	private String frontError;

	@Value("${app.interface.callback.url}")
	private String callbackURL;

	@Value("${app.interface.callbackurl.url}")
	private String callbackurl;

	@Value("${app.interface.partnerAccountCode}")
	private String partnerAccountCode;
	@Value("${app.interface.recordCode}")
	private String recordCode;
	@Value("${app.interface.agreementNo}")
	private String agreementNo;

	@Value("${app.interface.token.username}")
	private String username;
	@Value("${app.interface.token.password}")
	private String password;

	private Logger log = LoggerFactory.getLogger(getClass());
	Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();

	@Resource
	RestTemplate restTemplate; // 用他来访问http接口

	@Autowired
	private SpSaleLogDao spSaleLogDao;

	@Autowired
	private ScoreService scoreService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private ISequenceService iSequenceService;
	@Autowired
	private WeChatService weChatService;

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private ApplicantDao applicantDao;

	@Autowired
	private InsureService insureService;

	@Override
	public void payNsync(ServletRequest servletRequest, HttpServletRequest request, HttpServletResponse response, boolean isCalBack) {
		try {
			this.updateOrder(servletRequest, request, response, isCalBack);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}

	}

	@Override
	public void paySync(ServletRequest servletRequest, HttpServletRequest request, HttpServletResponse response, boolean isCalBack) {
		try {
			this.updateOrder(servletRequest, request, response, isCalBack);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}
	}

	/**
	 * Remarks: 统一处理回调<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月10日下午9:59:31<br>
	 * Project：liberty_sale_plat<br>
	 * 
	 * @param servletRequest
	 * @param request
	 * @param response
	 * @return
	 * @throws JAXBException
	 * @throws IOException
	 */
	private boolean updateOrder(ServletRequest servletRequest, HttpServletRequest request, HttpServletResponse response, boolean isCalBack)
			throws JAXBException, IOException {

		log.info("-------------------in1-------------------");

		TbSpSaleLog saleLog = new TbSpSaleLog();
		StringBuilder msg = new StringBuilder();
		saleLog.setOperation(TbSpSaleLog.OPERATION_PAY);
		saleLog.setRequestTime(new Date());
		// 核心支付成功后回掉传递的参数
		String responseXML = servletRequest.getParameter("responseXML");

		// String responseXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
		// + "<root><amount dataType=\"java.lang.Double\"
		// value=\"30.0\">30.00</amount><branchCode>51</branchCode><businessNo>9131055100180000992000</businessNo><businessSource>core</businessSource><businessType>policy</businessType><callbackCode>success</callbackCode><callbackMessage>尊敬的客户:您已支付成功,保单号是8131055100180000483000,利宝保险</callbackMessage><callbackStatus>1</callbackStatus><callbackUrl>http://10.132.21.40:9005/payment/servlet/BLEPaymentService</callbackUrl><createTime
		// dataType=\"java.sql.Timestamp\" value=\"1523255336000\"
		// returnType=\"java.util.Date\">2018-04-09 14:28:56</createTime><id
		// dataType=\"java.lang.Long\"
		// value=\"930000000010963\">930000000010963</id><noticeUrl>https://uat-lm.libertymutual.com.cn/sale/nol/pay/paySuccess</noticeUrl><payNo>930000000010963</payNo><payStatus>1</payStatus><payTime
		// dataType=\"java.sql.Timestamp\" value=\"1523255262000\"
		// returnType=\"java.util.Date\">2018-04-09
		// 14:27:42</payTime><payType>online</payType><platformId>chinapay-public</platformId><property00>哈哈</property00><property01>9131055100180000992000</property01><property02>哈哈</property02><property03/><property04/><property05/><property06/><property07/><property08/><property09/><property10/><property11/><property12/><property13/><property14/><property15/><property16/><property17/><property18/><property19/><redirectUrl>https://uat-lm.libertymutual.com.cn/sale/nol/pay/payRed</redirectUrl><remarks>哈哈,9131055100180000992000,哈哈</remarks><requestIp>10.132.30.212</requestIp><requestReferer>https://uat-soa.libertymutual.com.cn/payment/index</requestReferer><responseMessage/><securityCode>a126cca3aa7d14fa9622b50a19050490</securityCode><updateTime
		// dataType=\"java.sql.Timestamp\" value=\"1523255357000\"
		// returnType=\"java.util.Date\">2018-04-09 14:29:17</updateTime><version
		// dataType=\"java.lang.Long\" value=\"5\">5</version></root>";

		saleLog.setRequestData(responseXML);
		// saleLog.setResponseData(responseXML);
		boolean isCallBack = false;
		// msg.append("订单返回数据:" + responseXML);
		msg.append("<br>是否进行页面跳转:" + isCalBack + "   ");
		log.info(responseXML);
		log.info("-------------------解析XML-------------------");
		// 解析XML
		XmlBinder<Epayment> binder = new XmlBinder<Epayment>(Epayment.class);
		Epayment epayment = binder.unmarshal(responseXML);
		String regEx = "[^0-9]";
		Pattern pat = Pattern.compile(regEx);
		Matcher policy = pat.matcher(epayment.getCallbackMessage());
		String policyNum = policy.replaceAll("").trim();
		String proposalNo = epayment.getBusinessNo();
		// saleLog.setRequestData("保单号:" + proposalNo);
		// 车险回写

		log.info("------------------- 订单校验-------------------");
		// 订单校验
		List<TbSpOrder> orderList = orderDao.findByProposalNo(proposalNo);
		if (!"05".equals(proposalNo.substring(2, 4)) && (CollectionUtils.sizeIsEmpty(orderList) || orderList.size() > 1)) {
			log.info("保单号[" + epayment.getBusinessNo() + "]存在多条记录，如下");
			msg.append("<br>保单号存在多条记录");
			saleLog.setResponseData(msg.toString());
			spSaleLogDao.save(saleLog);
			for (TbSpOrder or : orderList) {
				log.info(BeanUtilExt.toJsonString(or));
			}
			return false;
		}
		TbSpOrder order = null;
		if (!"05".equals(proposalNo.substring(2, 4)) && orderList != null && orderList.size() > 0) {
			order = orderList.get(0);
		}

		if ("05".equals(proposalNo.substring(2, 4)) && StringUtils.isNotBlank(policyNum) && policyNum.startsWith("8")) {
			String carProposal = epayment.getProperty01();
			String[] carProList = carProposal.split(",");
			// String policyNo = "";
			TbSpOrder carOrder = null;
			List<TbSpOrder> orderCarList = null;
			Date date = new Date();
			log.info("-------------------05车险-------------------");
			for (int i = 0; i < carProList.length; i++) {
				orderCarList = orderDao.findByProposalNo(carProList[i]);
				proposalNo = carProList[i];
				Boolean isNewOrder = false;
				if (CollectionUtils.isEmpty(orderCarList)) {
					isNewOrder = true;
					carOrder = new TbSpOrder();
					carOrder.setProposalNo(proposalNo);// 投保单号
					carOrder.setCreateTime(date);
				} else {
					carOrder = orderCarList.get(0);
				}
				carOrder.setPayWay("7");// 支付类别
				// carOrder.setPolicyNo(policyNum);// 保单号
				carOrder.setPaymentNo(epayment.getPayNo());// 支付订单号
				carOrder.setPolicyNo(policyNum.substring(i * 22, (i + 1) * 22));
				if (isNewOrder) {
					carOrder = insureService.setQueryInfo(carOrder, proposalNo);
					carOrder.setOrderNo(iSequenceService.getOrderSequence(carOrder.getRiskCode()));
				}
				if (StringUtils.isBlank(policyNum)) {
					carOrder.setRemark(epayment.getCallbackMessage());
				}
				carOrder.setStatus(epayment.getPayStatus());
				if ("1".equals(epayment.getPayStatus())) {
					carOrder.setPayDate(epayment.getPayTime());
				}
				orderDao.save(carOrder);

			}

			// carOrder.setPayWay("7");// 支付类别
			// carOrder.setProposalNo(proposalNo);// 投保单号
			// carOrder.setPolicyNo(policyNum);// 保单号
			// carOrder.setPaymentNo(epayment.getPayNo());// 支付订单号
			//
			// TQueryPolicyResponseDto responseDto = policyService.queryDetail(proposalNo);
			// if (null != responseDto) {
			// if (CollectionUtils.isNotEmpty(responseDto.getPolicys())) {
			// TPolicyDto tPolicyDto = responseDto.getPolicys().get(0);
			// carOrder.setOrderNo(iSequenceService.getOrderSequence(tPolicyDto.getRiskcode()));//
			// 根据产品类型编码获取序列号订单号
			// carOrder.setAmount(Double.valueOf(tPolicyDto.getSumpremium()));// 总保费
			// carOrder.setRiskName(tPolicyDto.getRiskcname());// 险种名称
			// carOrder.setRiskCode(tPolicyDto.getRiskcode());
			// // 起止和创建以及更新时间
			// Date date = new Date();
			// carOrder.setCreateTime(date);
			// carOrder.setUpdateTime(date);
			// try {
			// date = (Date) new
			// SimpleDateFormat(DateUtil.DATE_TIME_PATTERN).parseObject(tPolicyDto.getStartdate());
			// carOrder.setStartDate(date);
			// date = (Date) new
			// SimpleDateFormat(DateUtil.DATE_TIME_PATTERN).parseObject(tPolicyDto.getEnddate());
			// carOrder.setEndDate(date);
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// carOrder.setApplicantName(tPolicyDto.getAppliname());// 投保人姓名
			// carOrder.setIdNo(tPolicyDto.getAppliIdentifynumber());// 投保人证件号
			// }
			// }
			//
			// if (StringUtils.isBlank(policyNum)) {
			// carOrder.setRemark(epayment.getCallbackMessage());
			// }
			// // order.setProposalNo(epayment.getBusinessNo());
			// // 订单状态回写
			// // order.setPaymentNo(epayment.getPayNo());
			// carOrder.setStatus(epayment.getPayStatus());
			// if ("1".equals(epayment.getPayStatus())) {
			// carOrder.setPayDate(epayment.getPayTime());
			// }
			try {
				spSaleLogDao.save(saleLog);
				// orderDao.save(carOrder);
				log.info("  存储redis :" + request.getSession().getId() + Constants.PAY_DOCUMENTNO);
				log.info("  redis信息 :" + epayment.getBusinessNo());
				// redisUtils.setWithExpireTime(request.getSession().getId() +
				// Constants.PAY_DOCUMENTNO, epayment.getBusinessNo(),
				// Constants.PAY_FIND_DOCUMENTNO_OUTTIME);
				redisUtils.setWithExpireTime(request.getSession().getId() + Constants.PAY_DOCUMENTNO, carProposal,
						Constants.PAY_FIND_DOCUMENTNO_OUTTIME);
				// redisUtils.setWithExpireTime(request.getSession().getId() +
				// Constants.PAY_POLICYNO, policyNo, Constants.PAY_FIND_DOCUMENTNO_OUTTIME);
				if (isCalBack) {
					redUrl(carOrder, response);
				}
				return true;
			} catch (Exception e) {
				log.info("支付回调保存订单异常：" + e.toString());
			}

			// 车险不回写 直接返回成功
			// redis.setWithExpireTime(request.getSession().getId() + Constants.POLICY_NUM,
			// policyNum,
			// Constants.PAY_FIND_DOCUMENTNO_OUTTIME);

			return true;
		} else if (StringUtils.isNotBlank(policyNum) && policyNum.startsWith("8")) {
			boolean isFristPay = false;
			// String orderPolicy = order.getPolicyNo();
			// if ((StringUtil.isNotEmpty(order.getStatus()) &&
			// order.getStatus().equals(epayment.getPayStatus()))
			// || (StringUtil.isNotEmpty(order.getPaymentNo()) &&
			// order.getPaymentNo().equals(epayment.getPayNo()))) {
			// log.info("保单[" + order.getPaymentNo() + "]已支付");
			// log.info("-------------------in已支付-------------------");
			// if (isCalBack) {
			// redUrl(order, response);
			// }
			// return true;
			// }
			if (StringUtils.isBlank(order.getPaymentNo())) {
				isFristPay = true;
			}
			if (StringUtils.isBlank(order.getPolicyNo())) {
				isCallBack = true;
			}
			msg.append("<br>设置支付信息到订单      policyNum:" + policyNum);
			if (StringUtils.isBlank(policyNum)) {
				order.setRemark(epayment.getCallbackMessage());
			}
			// 订单状态回写
			order.setPaymentNo(epayment.getPayNo());
			order.setStatus(epayment.getPayStatus());
			order.setPolicyNo(policyNum);
			if (StringUtils.isBlank(policyNum)) {
				order.setStatus(Constants.TBSPORDER_FAIL_PAY);
			}
			if (StringUtils.isNotBlank(policyNum) && policyNum.length() < 20) {
				order.setStatus(Constants.TBSPORDER_FAIL_PAY);
			}

			order.setUpdateTime(new Date());
			if ("1".equals(epayment.getPayStatus())) {
				order.setPayDate(new Date());
			}
			try {
				msg.append("<br>进行订单保存isFristPay:" + isFristPay);
				if (isFristPay) {
					orderDao.save(order);
				}

				log.info("  存储redis :" + request.getSession().getId() + Constants.PAY_DOCUMENTNO);
				log.info("  redis信息 :" + epayment.getBusinessNo());
				// redisUtils.setWithExpireTime(request.getSession().getId() +
				// Constants.PAY_DOCUMENTNO, epayment.getBusinessNo(),
				// Constants.PAY_FIND_DOCUMENTNO_OUTTIME);

				msg.append("<br>是否带有回调地址-:" + StringUtils.isNotBlank(order.getCallBackUrl()) + "-设置投保单号信息:" + isCallBack);
				if (StringUtils.isNotBlank(order.getCallBackUrl()) && isCallBack) {
					Callback(order);
				}
				if (isCalBack) {
					redUrl(order, response);
				}
			} catch (Exception e) {
				msg.append("<br>支付回调保存订单异常" + e.toString());
				log.info("支付回调保存订单异常：" + e.toString());
			}
			// boolean isBlankOrder = StringUtils.isBlank(orderPolicy);

			msg.append("<br>同步回调:" + isCalBack);
			saleLog.setResponseData(msg.toString());
			spSaleLogDao.save(saleLog);
			// if (isFristPay && isCallBack && isCalBack) {
			// // 积分
			// if (StringUtils.isBlank(orderPolicy) && StringUtils.isNotBlank(policyNum)) {
			// 同异步
			// if (isCalBack) {
			// saleLog.setResponseData(msg.toString());
			// spSaleLogDao.save(saleLog);
			// 是否新的保单（核心已回调）
			if (isCallBack) {
				msg.append("<br>新保,回调触发进行积分和推送!");
				newPolicyNo(order);
			}
			// }
			// }
			// if (StringUtils.isNotBlank(saleLog.getResponseData())) {
			// spSaleLogDao.save(saleLog);
			// }
			return true;
		} else {
			// order.setRemark("支付异常，没有获取到相应的投保单号!");
			if (epayment.getCallbackMessage().length() < 300) {
				String message = epayment.getCallbackMessage();
				if (message.indexOf("补登") > -1) {
					order.setStatus(TbSpOrder.STATUS_NO_POLIICY);
				} else {
					order.setStatus(TbSpOrder.STATUS_FAIL);
				}
				order.setRemark(epayment.getCallbackMessage());
			} else {
				msg.append("支付异常");
			}
			saleLog.setResponseData(msg.toString());
			orderDao.save(order);
			spSaleLogDao.save(saleLog);
			return true;

		}
	}

	public void redUrl(TbSpOrder order, HttpServletResponse response) {
		log.info("------------------订单回调-------------------");
		try {
			if (StringUtils.isNotBlank(order.getSuccessfulUrl())) {
				log.info("------ 有成功页面 --------:" + order.getSuccessfulUrl());
				String callBackUrl = order.getSuccessfulUrl();
				String pram = "";
				if (callBackUrl.indexOf("?") > -1) {
					pram = "&policy=" + order.getPolicyNo();
				} else {
					pram = "?policy=" + order.getPolicyNo();
				}
				if (StringUtils.isNotBlank(order.getDealUuid())) {
					pram += "&dealuuid=" + order.getDealUuid();
				}
				if (callBackUrl.indexOf("https") > -1) {
					pram = order.getSuccessfulUrl() + pram;
					response.sendRedirect(pram);
				} else {
					if (callBackUrl.indexOf("http") > -1) {
						pram = callbackurl + "?jumpurl=" + order.getSuccessfulUrl() + pram;
						response.sendRedirect(pram);
					} else {
						response.sendRedirect(frontSuccess);
					}
				}
			} else {
				log.info("------ 默认页面 --------:" + frontSuccess);
				response.sendRedirect(frontSuccess);
			}
		} catch (Exception e) {
			log.info("跳转地址异常" + e.toString());
		}
	}

	@Override
	public ServiceResult getPayData(RequestPayDto requestPayDto, HttpServletRequest request) {
		ServiceResult sr = new ServiceResult();
		Map<String, String> payMap = new HashMap<String, String>();
		String dateTime = Long.toString(new Date().getTime());
		String flowId = agreementNo + DateUtil.dateFromat(new Date().getTime(), DateUtil.DATE_TIME_PATTERN3)
				+ dateTime.substring(dateTime.length() - 5, dateTime.length());
		payMap.put("paymentURL", paymentURL);
		payMap.put("redirectUrl", redirectUrl); // redirectUrl
		payMap.put("callbackURL", callbackURL); // callbackURL
		payMap.put("documentNo", requestPayDto.getDocumentNo());
		payMap.put("agreementNo", agreementNo);
		payMap.put("recordCode", recordCode);
		payMap.put("partnerAccountCode", partnerAccountCode);
		payMap.put("flowId", flowId);
		payMap.put("riskCode", requestPayDto.getRiskCode());
		redisUtils.setWithExpireTime(request.getSession(true).getId() + Constants.PAY_DOCUMENTNO, requestPayDto.getDocumentNo(),
				Constants.PAY_FIND_DOCUMENTNO_OUTTIME);
		sr.setResult(payMap);
		return sr;
	}

	@Override
	public ServiceResult payInfoFind(RequestPayDto requestPayDto, HttpServletRequest request) {
		ServiceResult sr = new ServiceResult();

		Object obj = redisUtils.get(request.getSession().getId() + Constants.PAY_DOCUMENTNO);
		String documentNo = "";
		if (obj != null) {
			documentNo = obj.toString();
		}

		// String documentNo = null != obj ? obj.toString() : "";

		log.info("  获取redis :" + request.getSession().getId() + Constants.PAY_DOCUMENTNO);
		log.info("  redis信息 :" + documentNo);
		if (StringUtils.isBlank(documentNo)) {
			sr.setResult("未查询到对应信息");
			sr.setFail();
			return sr;
		}
		// String branchCodeSub=order.getProposalNo().substring(6, 8);
		// List<TbSysHotarea> areaList = null;
		// if("33".equals(branchCodeSub)){
		// areaList =
		// tbSysHotareaDao.findLikeBranchCodeLike(order.getProposalNo().substring(6,
		// 10));
		// }else{
		// areaList = tbSysHotareaDao.findLikeBranchCodeLike(branchCodeSub);
		// }
		// order.setInvoiceStatus(areaList.get(0).getInvoiceStatus());
		// order.setInsurancePolicyStatus(areaList.get(0).getInsurancePolicyStatus());
		// if("05".equals(documentNo.substring(2,4))) {
		//
		//
		// }else {
		//
		// }
		// List<TbSpOrder> order = null;
		// String[] proSt = documentNo.split(",");
		// TbSpOrder resOrder = new TbSpOrder();
		// StringBuilder resPolicyNo = new StringBuilder(); //保单号
		// stringbuilder resProposalNo = new stringbuilder(); //投保单号
		// stringbuilder
		//
		// for(int i=0;i<proSt.length;i++) {
		//
		// }
		String[] stArray = documentNo.split(",");
		List<TbSpOrder> orderList = new ArrayList<TbSpOrder>();
		for (int i = 0; i < stArray.length; i++) {
			List<TbSpOrder> order = orderDao.findByProposalNo(stArray[i]);
			TbSpOrder resOrder = new TbSpOrder();
			if (order.size() > 0) {
				TbSpOrder or = order.get(0);
				String areaCode = or.getProposalNo().substring(6, 10);
				String branchCodeSub = or.getProposalNo().substring(6, 8);
				String doPolicy = or.getProposalNo().substring(2, 4);
				List<TbSysHotarea> areaList = null;
				areaList = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
				if (areaList == null) {
					or.setInvoiceStatus("0");
					or.setInsurancePolicyStatus("0");
				} else {
					if (areaList.size() == 0) {
						or.setInvoiceStatus("0");
						or.setInsurancePolicyStatus("0");
					} else {
						or.setInvoiceStatus(areaList.get(0).getInvoiceStatus());
						or.setInsurancePolicyStatus(areaList.get(0).getInsurancePolicyStatus());
					}
				}

				// if ("33".equals(branchCodeSub)) {
				// areaList =
				// tbSysHotareaDao.findLikeBranchCodeLike(or.getProposalNo().substring(6, 10));
				// } else {
				// areaList = tbSysHotareaDao.findLikeBranchCodeLike(branchCodeSub);
				// }
				// or.setInvoiceStatus(areaList.get(0).getInvoiceStatus());
				// 车险禁止下载电子保单 只有北京可以下载
				if ("05".equals(doPolicy)) {
					or.setInsurancePolicyStatus(TbSpOrder.STATUS_PROHIBIT);
					if ("11".equals(branchCodeSub)) {
						or.setInsurancePolicyStatus(TbSpOrder.STATUS_ALLOW);
					}
				}

				or = this.getUserSubscribe(or);

				orderList.add(or);

			} else {
				sr.setResult("没有查询到对应的信息");
				sr.setFail();
				return sr;
			}
		}
		sr.setResult(orderList);
		sr.setSuccess();

		return sr;
	}

	/**
	 * Remarks: 获取用户关注状态<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2018年1月4日下午2:24:37<br>
	 * Project：liberty_sale_plat<br>
	 * 
	 * @param or
	 * @return
	 */
	private TbSpOrder getUserSubscribe(TbSpOrder or) {
		TbSpUser user = new TbSpUser();
		user.setWxSubscribe("0");// 默认需要关注
		// 已登录购买
		if (StringUtils.isNotBlank(or.getUserId())) {
			List<TbSpUser> users = userDao.findByUserCodeBoth(or.getUserId(), or.getUserId());
			// 已注册用户
			for (TbSpUser u : users) {
				// 多账户都已关注公众号
				if ("1".equals(u.getWxSubscribe())) {
					user.setWxSubscribe("1");
				} else {
					// 一个未关注则需要提示关注
					user.setWxSubscribe("0");
				}
			}
		}
		or.setUser(user);// 记录用户信息
		return or;
	}

	@Override
	public ServiceResult queryPayList(TQueryPolicyRequstDto requestPayDto, HttpServletRequest request) {
		// TODO Auto-generated method stub 调用 第三方
		ServiceResult rs = new ServiceResult();
		rs.setSuccess();
		Object datePay = redisUtils.get(Constants.POLICYS_AUTHEN + ":" + request.getSession(true).getId());
		if (null == datePay) {
			rs.setFail();
			rs.setResult("查询失败！");
			return rs;
		} else {
			requestPayDto = (TQueryPolicyRequstDto) datePay;
		}
		requestPayDto.setId(requestPayDto.getId());
		requestPayDto.setPolicyNo(requestPayDto.getPolicyNo());
		requestPayDto.setMobileNo(requestPayDto.getMobileNo());

		// requestPayDto.setId("140225199405160812");
		// requestPayDto.setPolicyNo("8127261100170000040000");
		// requestPayDto.setMobileNo("");

		// requestPayDto.setFlowId("LBN0031503283032322");
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.QUERY_PAYLIST_URL.getUrlKey());
		requestPayDto.setPartnerAccountCode(sysServiceInfo.getUserName());
		requestPayDto.setFlowId(sysServiceInfo.getUserName() + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3) + new Date().getTime());
		// sysServiceInfo.setUrl("http://10.132.21.14:8850/queryPayInfo.do");
		TQueryPayInfoResponseDto responseDto = new TQueryPayInfoResponseDto();
		try {
			HttpEntity<TQueryPolicyRequstDto> requestEntity = new HttpEntity<TQueryPolicyRequstDto>(requestPayDto,
					RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword()));

			responseDto = restTemplate.postForObject(sysServiceInfo.getUrl(), requestEntity, TQueryPayInfoResponseDto.class);
		} catch (RestClientException e) {
			log.error(e.getMessage(), e);
			rs.setAppFail();
			rs.setResult("APPERROR:调用服务失败,请联系管理员！");
		}

		rs.setResult(responseDto);
		if (responseDto.getStatus() != null && responseDto.getStatus()) {
			rs.setSuccess();
		} else {
			rs.setFail();
		}
		return rs;
	}

	@Override
	public ServiceResult callbackUrl(String documentNo, Boolean isJump, HttpServletResponse response) {
		List<TbSpOrder> orderList = orderDao.findByProposalNo(documentNo);
		ServiceResult sr = new ServiceResult();
		if (orderList != null && orderList.size() != 0) {
			TbSpOrder order = orderList.get(0);
			newPolicyNo(order);
			sr = Callback(orderList.get(0));
			try {
				if (isJump) {
					redUrl(order, response);
				}
			} catch (Exception e) {
				sr.setFail();
				sr.setResult("跳转地址错误");
				log.error("支付回调{}", e.getMessage(), e);
			}
		} else {
			sr.setFail();
			sr.setResult("没有查询到对应的保单号");
		}
		return sr;
	}

	@Override
	public ServiceResult updateOrderState(Object data) {
		TbSpSaleLog saleLog = new TbSpSaleLog();
		saleLog.setOperation("核心状态太更新");
		String test = BeanUtilExt.toJsonString(data);
		saleLog.setRequestData(test);
		log.info("-----------------------------------------");
		log.info(test);
		spSaleLogDao.save(saleLog);
		return null;
	}

	public ServiceResult Callback(TbSpOrder order) {
		ServiceResult sr = new ServiceResult();

		TbSpSaleLog saleLog = new TbSpSaleLog();
		saleLog.setOperation("回调第三方");
		saleLog.setRequestTime(new Date());
		if (StringUtils.isBlank(order.getCallBackUrl()) || StringUtils.isBlank(order.getPolicyNo()) || !order.getPolicyNo().startsWith("8")) {
			saleLog.setRequestData(order.getPolicyNo());
			saleLog.setRequestData("该单子不允许回调!");
			sr.setFail();
			sr.setResult("该单子不允许回调!");
			return sr;
		}
		OrderInfo orInfo = new OrderInfo();
		// orInfo.setAccessUrl(order.getAccessUrl());
		orInfo.setUserId(order.getSingleMember()); // 业务员
		orInfo.setCityId(order.getInsureCity()); // 销售城市
		orInfo.setOrderAmount(""); // 订单原价金额
		orInfo.setOrderDiscount(""); // 订单优惠总金额
		orInfo.setFinalAmount(order.getAmount().toString()); // 订单最终应付金额
		orInfo.setCommissionRate(""); // 手续费率
		orInfo.setFee(""); // 手续费
		orInfo.setCircPaymentNo(order.getPaymentNo()); // 付费流水号
		orInfo.setStatus(order.getStatus()); // 订单状态
		orInfo.setDealuuid(order.getDealUuid());
		orInfo.setPayNode("在线支付"); // 支付方式
		orInfo.setPayNotifyDate(order.getPayDate()); // 支付时间
		orInfo.setPayPerson(order.getApplicantName()); // 付款人
		orInfo.setApplyPolicyNo(order.getProposalNo()); // 投保单号
		orInfo.setPolicyNo(order.getPolicyNo()); // 保单号
		orInfo.setProtocolNo(order.getAgreementNo());
		orInfo.setApplyPolicyDate(order.getCreateTime());
		orInfo.setNumberOfInsured("1");
		if (StringUtil.isNotEmpty(order.getShareUid())) {
			String salt = md5PwdEncoder.encodePassword(order.getShareUid(), "HENGHUA");
			String signature = md5PwdEncoder.encodePassword(order.getProposalNo(), salt);
			orInfo.setSignature(signature);
		}
		// orInfo.set

		JSONArray array = JSONArray.parseArray(order.getOrderDetail());
		List<CrossSaleKind> kinds = array.toJavaList(CrossSaleKind.class);
		Float sum = 0F;
		for (int i = 0; i < kinds.size(); i++) {
			Float adultMax = Float.parseFloat(kinds.get(i).getAdultMax());
			sum += adultMax;
		}
		orInfo.setAdultMaxSum(sum.toString());
		orInfo.setKinds(kinds);
		Product product = new Product();
		product.setProductName(order.getProductName());
		product.setProductCode(order.getPlanCode());
		product.setProductAmount(order.getAmount().toString());
		product.setRiskCode(order.getPlanRiskCode());
		product.setPlanCode(order.getPlanId());
		product.setBeginDate(order.getStartDate());
		product.setEndDate(order.getEndDate());
		orInfo.setProduct(product);

		List<TbSpApplicant> appList = applicantDao.findOrderNo(order.getOrderNo());
		List<Insured> insuredList = new ArrayList<Insured>();
		for (int i = 0; i < appList.size(); i++) {
			TbSpApplicant app = appList.get(i);
			if ("1".equals(app.getType())) { // 1投保人,2被保人
				Appnt appnt = new Appnt();
				appnt.setAppntName(app.getName());
				appnt.setAppntCertificationCode(app.getCarId());
				appnt.setAppntCertificationType(app.getCarType());
				appnt.setAppntBirthday(app.getBirth());
				appnt.setAppntAddress(order.getAddress());
				appnt.setAppntEmail(app.getEmail());
				appnt.setMobile(app.getMobile());
				appnt.setAppntSex(app.getSex());
				orInfo.setAppntPerson(appnt);
			} else {
				Insured insure = new Insured();
				insure.setBirthday(app.getBirth());
				insure.setInsuredCertificationCode(app.getCarId());
				insure.setInsuredCertificationType(app.getCarType());
				insure.setAddress(order.getAddress());
				insure.setInsuredName(app.getName());
				insure.setInsuredEmail(app.getEmail());
				insure.setInsuredMobile(app.getMobile());
				insure.setSex(app.getSex());
				insure.setRelation(app.getRelation());
				insuredList.add(insure);
			}
		}
		orInfo.setInsuredList(insuredList);
		// String test= JSON.toJSONString(orInfo);
		// HttpHeaders headers = new HttpHeaders();
		// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		// headers.setContentLength(BeanUtilExt.toJsonString(orInfo).length());
		// headers.setConnection("Keep-Alive");
		// headers.set("Charset", "UTF-8");
		// HttpEntity<String> requestEntity = new
		// HttpEntity<String>(BeanUtilExt.toJsonString(orInfo), headers);
		try {
			// System.out.println(BeanUtilExt.toJsonString(requestEntity));
			//
			String callBackUrl = order.getCallBackUrl();
			String pram = "";
			if (callBackUrl.indexOf("?") > -1) {
				pram = "&policy=" + order.getPolicyNo();
			} else {
				pram = "?policy=" + order.getPolicyNo();
			}
			if (StringUtils.isNotBlank(order.getDealUuid())) {
				pram += "&dealuuid=" + order.getDealUuid();
			}
			saleLog.setRequestData(BeanUtilExt.toJsonString(orInfo) + "     URL:" + callBackUrl + pram);
			String resData = HttpAndHttpsUtil.postJsonReturnJsonSt(callBackUrl + pram, BeanUtilExt.toJsonString(orInfo), "UTF-8");
			// System.out.println(n);
			saleLog.setResponseData(resData);
			// Object res =
			// restTemplate.postForObject("http://182.92.1.74:17668/callback/liberty/h5CallBack.do",
			// requestEntity, Object.class);
			sr.setSuccess();
		} catch (Exception e) {
			saleLog.setResponseData(e.toString());
			sr.setFail();
			log.error("支付回调{}", e.getMessage(), e);
		}
		spSaleLogDao.save(saleLog);

		// Map map = (Map) redis.get(Constants.SYS_SERVICE_INFO);
		// SysServiceInfo sysServiceInfo = (SysServiceInfo)
		// map.get(CoreServiceEnum.CALL_BACK_URL.getUrlKey());

		// CallBack call = new CallBack();
		// call.setTopic("BOBTEST");
		// call.setTag("TEST");
		// call.setKey(DateUtil.getStringDateYyMMdd() + UUID.getShortUuid());
		// call.setTimeout("15000");
		// call.setCharset("utf-8");
		// CallBackData callData = new CallBackData();
		// callData.setRequestType("POST");
		// callData.setUrl(order.getCallBackUrl());
		// callData.setData(JSON.toJSONString(orInfo));
		// call.setBody(callData);

		// HttpEntity<CallBack> requestEntity = new HttpEntity<CallBack>(call,
		// RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(),
		// sysServiceInfo.getPassword()));
		// BaseResponse res = restTemplate.postForObject(sysServiceInfo.getUrl(),
		// requestEntity, BaseResponse.class);

		return sr;

	}

	public void newPolicyNo(TbSpOrder rewriteOrder) {
		// 积分
		TbSpScoreLogIn inScore = null;
		// 活动和抽奖返回信息
		Map<String, Object> resultMap = Maps.newHashMap();
		// 渠道层级积分发放
		List<TbSpScoreLogIn> scoreList = Lists.newArrayList();
		// 积分用户
		TbSpUser scoreUser = null;

		if (StringUtils.isNotBlank(rewriteOrder.getUserId()) || StringUtils.isNotBlank(rewriteOrder.getRefereeId())) {
			log.info("------rewrite.getUserId()-----{}", rewriteOrder.getUserId());
			log.info("------推荐人-----{}", rewriteOrder.getRefereeId());
			@SuppressWarnings("unchecked")
			List<TbSpScoreConfig> scoreconfig = (List<TbSpScoreConfig>) redisUtils.get(Constants.SCORE_CONFIG_INFO);
			if (CollectionUtils.isEmpty(scoreconfig)) {
				scoreconfig = scoreConfigDao.findAllConfig();
				redisUtils.set(Constants.SCORE_CONFIG_INFO, scoreconfig);
			}
			if (Constants.TRUE.equals(scoreconfig.get(0).getRuleSwitch())) {
				log.info("------规则发放开关是开启状态,支付后开始积分记录-----");

				scoreUser = scoreService.scoreUser(rewriteOrder);
				log.info("------积分送到-----{}", scoreUser.getUserCode());
				if (null != scoreUser) {
					// // 自主注册
					// if (Constants.USER_REGISTER_TYPE_0.equals(scoreUser.getRegisterType())) {//
					// // 自主注册获得积分
					// // inScore =
					// // scoreService.ruleInScore(Integer.parseInt(rewriteOrder.getProductId()),
					// // rewriteOrder.getPolicyNo(),
					// // rewriteOrder.getAmount(), rewriteOrder.getStartDate());
					// inScore = scoreService.ruleInScore(rewriteOrder, scoreUser);
					// }
					// // 层级渠道
					// if (Constants.USER_REGISTER_TYPE_1.equals(scoreUser.getRegisterType())
					// || Constants.USER_REGISTER_TYPE_2.equals(scoreUser.getRegisterType())) {
					// // 渠道层级积分
					//
					// scoreList = scoreService.channelInScore(rewriteOrder, scoreUser);
					// } else {
					// // 层级个人用户
					//
					// inScore = scoreService.ruleInScore(rewriteOrder, scoreUser);
					// if (null != inScore) {
					// // 加送上两级推广积分
					// scoreList = scoreService.personalInScore(rewriteOrder, scoreUser);
					// }
					// }

					// 出行宝送积分
					scoreList = scoreService.cxbInScore(rewriteOrder, scoreUser);

				}
			}
			// 活动和抽奖返回信息
			resultMap = activityService.grantScore(rewriteOrder.getBranchCode(), Constants.ISSUE_ACTIVITY_DO, null, rewriteOrder);
		}

		// 1=才推送
		// if ("1".equals(inScore.getStatus())) {
		// 给渠道/好友推送出单消息
		sendWeChatMsgByFriendsInsure(rewriteOrder, scoreList, scoreUser);
		// }

		// 活动
		@SuppressWarnings("unchecked")
		List<TbSpScoreLogIn> aclist = (List<TbSpScoreLogIn>) resultMap.get("acList");// 活动记录
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> sendMsgList = (List<Map<String, Object>>) resultMap.get("sendMsgList");// 抽奖消息发送记录

		log.info("inScore=====>{}", JSON.toJSONString(inScore));
		StringBuffer remarks = new StringBuffer();
		// // 状态=1=可追加推送内容
		// if (inScore != null && "1".equals(inScore.getStatus()) &&
		// inScore.getReChangeScore() != null
		// && inScore.getReChangeScore().compareTo(0.0D) > 0) {
		// // 订单宝豆
		// remarks.append(String.format(Constants.SMS_BY_PAY_BEANS,
		// inScore.getReChangeScore()));
		// }

		// 活动宝豆微信消息推送
		if (CollectionUtils.isNotEmpty(aclist)) {
			remarks.append(Constants.SMS_BY_ACTIVITY_BEANS_PREFIX);
			for (TbSpScoreLogIn scoreLogIn : aclist) {
				// 状态=1=可推送，宝豆大于0才追加备注
				if ("1".equals(scoreLogIn.getStatus()) && scoreLogIn.getReChangeScore() > 0) {
					remarks.append(String.format(Constants.SMS_BY_ACTIVITY_BEANS_SUFFIX, scoreLogIn.getReason(), scoreLogIn.getReChangeScore()));
					if (scoreLogIn.getId().compareTo(aclist.get(aclist.size() - 1).getId()) == 0) {
						// 最后一个活动
						remarks.append("。");
					} else {
						remarks.append("；");
					}
				}
			}
		}
		if (weChatService.sendOderWeChatMsg(rewriteOrder, remarks.toString())) {
			log.info("公众号成功推送【出单】消息==成功");
		}
		// 抽奖微信消息推送
		if (CollectionUtils.isNotEmpty(sendMsgList)) {
			for (Map<String, Object> tempMap : sendMsgList) {
				TbSpUser user = (TbSpUser) tempMap.get("user");
				String title = tempMap.get("title").toString();
				title = StringUtils.isNotBlank(title) ? "（" + title + "）" : "";

				// 推荐人不为空，且推荐人已关注公众号，则发送消息
				if (null != user && "1".equals(user.getWxSubscribe())) {

					String content = String.format(Constants.SMS_BY_ACTIVITY_TIMES, 1, title);
					boolean flag = weChatService.sendTextMessageSingle(user.getWxOpenId(), MessageType.REQ_MESSAGE_TYPE_TEXT, content);

					// 日志
					TbSpSaleLog saleLog = new TbSpSaleLog();
					saleLog.setOperation(TbSpSaleLog.WECHAT_MSG);
					saleLog.setUserCode(user.getUserCode());
					saleLog.setMark(TbSpSaleLog.WECHAT_MSG);
					saleLog.setRequestTime(new Date());
					saleLog.setRequestData(
							"user：" + JSON.toJSONString(user) + "<br>,rewriteOrder：" + JSON.toJSONString(rewriteOrder) + "<br>,content：" + content);
					saleLog.setResponseData("【抽奖】推送结果：" + flag);
					spSaleLogDao.save(saleLog);
				}
			}
		}
	}

	/** 
	 * 给渠道/好友推送出单消息<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2018年4月3日下午6:16:26<br>
	 * @param rewriteOrder
	 * @param scoreList
	 * @param scoreUser
	 */
	private void sendWeChatMsgByFriendsInsure(TbSpOrder rewriteOrder, List<TbSpScoreLogIn> scoreList, TbSpUser scoreUser) {
		log.info("渠道/个人出单推送微信消息列表：{}", JSON.toJSONString(scoreList));

		// 渠道积分推送
		if (CollectionUtils.isNotEmpty(scoreList)) {
			String nowTime = DateUtil.getStringDate();

			for (TbSpScoreLogIn scoreLogIn : scoreList) {
				// 出单人或层级用户和积分不为空，且积分不能小于0
				if (scoreUser == null || scoreLogIn == null || scoreLogIn.getReChangeScore() == null
						|| scoreLogIn.getReChangeScore().compareTo(0.0D) <= 0) {
					continue;
				}

				// 出单或好友的名称
				String userName = "";
				TbSpUser acceptMsgUser = scoreLogIn.getUser();// 接收消息用户
				String formatStr = Constants.SMS_BY_FRIENDS_PERSONAL_INSURE_ZJ;// 默认直接好友模板

				// 间接好友
				if (Constants.INDIRECT_FRIEND_ISSUE.equals(scoreLogIn.getChangeType())) {
					TbSpUser friendUser = userDao.findByUserCode(scoreUser.getComCode());// 查询上级用户

					// 出单的好友名称
					userName = friendUser.getUserName();
					userName = StringUtils.isBlank(userName) ? friendUser.getNickName() : userName;

					// 顶级用户收到的信息模板
					String remarks = String.format(Constants.SMS_BY_FRIENDS_PERSONAL_INSURE_JJ, userName, nowTime, scoreLogIn.getReChangeScore());

					// 被推送人不为空，且已关注公众号，且好友不为空
					if (acceptMsgUser != null && "1".equals(acceptMsgUser.getWxSubscribe()) && scoreUser != null) {
						// 间接上级推送消息
						send(rewriteOrder, acceptMsgUser, remarks);
					}
				} else {
					// 出单人名称
					userName = scoreUser.getUserName();
					userName = StringUtils.isBlank(userName) ? scoreUser.getNickName() : userName;

					String remarks = "";// 推送内容
					// 注册类型
					if (Constants.USER_REGISTER_TYPE_1.equals(scoreUser.getRegisterType())
							|| Constants.USER_REGISTER_TYPE_2.equals(scoreUser.getRegisterType())) {
						// 渠道
						remarks = String.format(Constants.SMS_BY_FRIENDS_CHANNEL_INSURE, userName, nowTime, scoreLogIn.getReChangeScore());
					} else {
						// 层级个人用户
						remarks = String.format(formatStr, userName, nowTime, scoreLogIn.getReChangeScore());
					}

					// 被推送人不为空，且已关注公众号，且好友不为空
					if (acceptMsgUser != null && "1".equals(acceptMsgUser.getWxSubscribe()) && scoreUser != null) {
						// 推送消息
						send(rewriteOrder, acceptMsgUser, remarks);
					}
				}
			} // 循环end
		}
	}

	/**推送消息*/
	private void send(TbSpOrder rewriteOrder, TbSpUser acceptMsgUser, String remarks) {
		boolean flag = weChatService.sendTextMessageSingle(acceptMsgUser.getWxOpenId(), MessageType.REQ_MESSAGE_TYPE_TEXT, remarks);
		log.info("公众号成功推送【渠道/好友】【出单】消息==" + flag);

		// 日志
		TbSpSaleLog saleLog = new TbSpSaleLog();
		saleLog.setOperation(TbSpSaleLog.WECHAT_MSG);
		saleLog.setUserCode(acceptMsgUser.getUserCode());
		saleLog.setMark(TbSpSaleLog.WECHAT_MSG);
		saleLog.setRequestTime(new Date());
		saleLog.setRequestData("acceptMsgUser：" + JSON.toJSONString(acceptMsgUser) + "<br>,TbSpOrder：" + JSON.toJSONString(rewriteOrder)
				+ "<br>,content：" + remarks.toString());
		saleLog.setResponseData("【宝豆】推送结果：" + flag);
		spSaleLogDao.save(saleLog);
	}

	@Override
	public ServiceResult callbackUpdateOrder(CallBackRequestDto cbrd) {
		log.info("....jinru....callback.....");
		StringBuilder msg = new StringBuilder();
		String jsonCbrd = JSONObject.toJSONString(cbrd, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
		log.info(jsonCbrd);
		TbSpSaleLog saleLog = new TbSpSaleLog();
		boolean isNeedCallBack = false;
		boolean isFristUpdate = false;
		boolean siTb = false;
		saleLog.setOperation(TbSpSaleLog.CALLBACK);
		saleLog.setRequestTime(new Date());

		jsonCbrd = jsonCbrd + "     投保单号:" + cbrd.getProposalNo();
		saleLog.setRequestData(jsonCbrd);
		List<TbSpOrder> order = orderDao.findProposalNo(cbrd.getProposalNo());
		if (CollectionUtils.isNotEmpty(order)) {
			String state = resetState(cbrd.getStatus());
			// 订单回写
			TbSpOrder rewrite = order.get(0);
			try {
				// if(StringUtils.isNotBlank(cbrd.getCurrentPremium())) {
				// rewrite.setAmount(Double.parseDouble(cbrd.getCurrentPremium()));
				// }
				if (!rewrite.getStatus().equals(state)) {
					msg.append("  需要更新订单状态  前:" + rewrite.getStatus() + "  后:" + state);
					isNeedCallBack = true;
				}
				// 状态3在核心非车为 批退->自动核保
				// if ("3".equals(cbrd.getStatus())) {
				// msg.append(" 批退: 订单当前状态" + rewrite.getStatus() + " 状态为3：批退->自动核保" + "状态更新:14
				// 退积分");
				// state = "14";
				// isNeedCallBack = true;
				// siTb = true;
				// }

				if (StringUtils.isNotBlank(cbrd.getEndorType())) {
					if ("21".equals(cbrd.getEndorType())) {
						msg.append("  批退:   订单当前状态" + rewrite.getStatus() + " EndorType:" + cbrd.getEndorType() + "状态更新:14   退积分");
						state = "14";
						isNeedCallBack = true;
						siTb = true;
					} else if ("pg".equals(cbrd.getEndorType())) {
						msg.append("  批改:   订单当前状态" + rewrite.getStatus() + " EndorType:" + cbrd.getEndorType() + "状态更新:15");
						state = "15";
						isNeedCallBack = true;
						if (StringUtils.isNotBlank(cbrd.getOldPremium()) && StringUtils.isNotBlank(cbrd.getCurrentPremium())) {
							msg.append(" 修改价格 :<br>原订单价格:Amount-" + rewrite.getAmount() + "  OldPremium:" + rewrite.getOldPremium());
							rewrite.setAmount(Double.parseDouble(cbrd.getCurrentPremium()));
							rewrite.setOldPremium(Double.parseDouble(cbrd.getOldPremium()));
							msg.append(" <br>修改完成后:Amount-" + rewrite.getAmount() + "  OldPremium:" + rewrite.getOldPremium());
						}
						// 设置批单号
						rewrite.setEndorseNo(cbrd.getEndorseNo());
						// 设置投保人信息
						if (StringUtils.isNotBlank(cbrd.getAppliName())) {
							rewrite.setApplicantName(cbrd.getAppliName());
						}
					} else if ("03".equals(cbrd.getEndorType())) {
						msg.append("  保单遗失  :   订单当前状态" + rewrite.getStatus() + " EndorType:" + cbrd.getEndorType() + "状态更新:16  退积分");
						state = "16";
						isNeedCallBack = true;
						siTb = true;
					} else if ("19".equals(cbrd.getEndorType())) {
						msg.append("  保单注销   :   订单当前状态" + rewrite.getStatus() + " EndorType:" + cbrd.getEndorType() + "状态更新:17  退积分");
						state = "17";
						isNeedCallBack = true;
						siTb = true;
					}
				}

				if ("1".equals(state) && StringUtils.isBlank(cbrd.getEndorType()) && StringUtils.isBlank(rewrite.getPolicyNo())) {
					rewrite.setPayDate(new Date());
					rewrite.setPolicyNo(cbrd.getPolicyNo());
					msg.append("新保需要送积分   ");
					isFristUpdate = true;
				}
				rewrite.setUpdateTime(new Date());
				rewrite.setStatus(state);

				// if (StringUtils.isNotBlank(cbrd.getOldPremium())) {
				// rewrite.setOldPremium(rewrite.getAmount());
				// rewrite.setAmount(Double.parseDouble(cbrd.getOldPremium()));
				// msg.append(" 更新价格 原订单："+rewrite.getAmount() + " 更新后" +
				// cbrd.getOldCarshipPremium());
				// rewrite.setOldPremium(Double.parseDouble(cbrd.getOldPremium()));
				// }

				if (StringUtils.isNotBlank(cbrd.getPolicyNo()) && StringUtils.isBlank(rewrite.getPolicyNo())) {
					isNeedCallBack = true;
					rewrite.setPolicyNo(cbrd.getPolicyNo());
					rewrite.setStatus(TbSpOrder.STATUS_EFFECTIVE);
					msg.append("  订单保单号不存在更新保单以及状态:" + cbrd.getPolicyNo());
				}
				// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				// rewrite.setStartDate(sdf.parse(cbrd.getStartDate()));
				// rewrite.setEndDate(sdf.parse(cbrd.getEndDate()));
				if (StringUtils.isNotBlank(cbrd.getPayWay())) {
					rewrite.setPayWay(cbrd.getPayWay());
				}
				// rewrite.setApplicantName(cbrd.getAppliName());
				if (StringUtils.isNotBlank(cbrd.getUnderWriteFailReason()) && !"null".equals(cbrd.getUnderWriteFailReason())) {
					rewrite.setRemark(cbrd.getUnderWriteFailReason());
				}
				msg.append("success");
				orderDao.save(rewrite);
				if (isNeedCallBack) {
					msg.append(" 回调");
					log.info("...---------------------核心回调回调-----------------..");
					Callback(rewrite);
				}
			} catch (Exception e) {
				msg.append("回调:保存订单失败" + e.toString());
				e.printStackTrace();
			}

			saleLog.setResponseData(msg.toString());
			spSaleLogDao.save(saleLog);

			if (isFristUpdate) {
				newPolicyNo(rewrite);
			}

			if (siTb) {
				// 积分退保
				List<TbSpScoreConfig> scoreconfig = (List<TbSpScoreConfig>) redisUtils.get(Constants.SCORE_CONFIG_INFO);
				if (CollectionUtils.isEmpty(scoreconfig)) {
					scoreconfig = scoreConfigDao.findAllConfig();
					redisUtils.set(Constants.SCORE_CONFIG_INFO, scoreconfig);
				}
				// 开关是否开启
				// if (Constants.TRUE.equals(scoreconfig.get(0).getTbreback())) {
				// TbSpScoreLogIn orderin = scoreLogInDao.findByPolicyNo(cbrd.getPolicyNo());
				// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				// String s = sdf.format(new Date());
				// try {
				// Date date = sdf.parse(s);
				// if (orderin.getEffictiveDate().compareTo(date) > 0) {// 投保获得的积分还未生效
				// // 直接修改待生效的实发=应发;
				// scoreService.ruleOutScore(orderin.getPolicyNo(), orderin.getUserCode());
				// } else {
				// scoreService.outScore(Constants.CHANGE_TYYPE_TB, orderin.getUserCode(),
				// orderin.getReChangeScore(), "退保", orderin.getPolicyNo());
				// }
				// } catch (ParseException e) {
				// e.printStackTrace();
				// }
				// }

				// 开关是否开启
				if (Constants.TRUE.equals(scoreconfig.get(0).getTbreback())) {
					log.info("开始退保退积分cbrd.getPolicyNo()。。。。。。。{}", cbrd.getPolicyNo());
					log.info("开始退保退积分order.getPolicyNo()。。。。。。。{}", rewrite.getPolicyNo());
					List<TbSpScoreLogIn> orderins = scoreLogInDao.findByPolicyNo(rewrite.getPolicyNo());
					if (CollectionUtils.isNotEmpty(orderins)) {
						for (TbSpScoreLogIn orderin : orderins) {
							TbSpSaleLog tbLog = new TbSpSaleLog();
							tbLog.setOperation("退保扣减积分");
							tbLog.setRequestTime(new Date());
							tbLog.setRequestData(orderin.getUserCode() + "退保扣减积分:" + orderin.getReChangeScore());
							// 直接扣减一笔
							log.info("退保{}", orderin.getUserCode());
							log.info("退保扣减积分{}", orderin.getReChangeScore());
							// 判断是否生效
							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
							String thisday = df.format(new Date());
							Date today;
							try {
								today = df.parse(thisday);
								String remark = "";
								TbSpUser scoreU = userDao.findByUserCode(orderin.getUserCode());
								TbSpUser firstScoreU = scoreService.scoreUser(rewrite);
								if (Constants.USER_REGISTER_TYPE_0.equals(scoreU.getRegisterType())) {
									if (StringUtils.isNotBlank(scoreU.getComCode())) {
										if (firstScoreU.getUserCode().equals(scoreU.getUserCode())) {
											remark = "一般退保";
										} else if (scoreU.getUserCode().equals(firstScoreU.getComCode())) {
											remark = "好友签单退保";
										} else {
											remark = "间接好友签单退保";
										}
									} else {
										if (!scoreU.getUserCode().equals(firstScoreU.getUserCode())) {
											remark = "间接好友签单退保";
										} else {
											// 自主注册退保
											remark = "一般退保";
										}
									}
								} else {
									// 渠道出单退保
									remark = "渠道退保";
								}

								if (orderin.getEffictiveDate().getTime() > today.getTime()) {
									TbSpScoreLogOut out = scoreService.outInvalidScore(orderin, remark);
									tbLog.setResponseData(out.toString());
								} else {
									List<TbSpScoreLogIn> tb = scoreService.outScore(orderin.getChangeType(), orderin.getUserCode(),
											orderin.getReChangeScore(), remark, rewrite.getPolicyNo());
									tbLog.setResponseData(tb.toString());
								}
								tbLog.setMark(remark);
								tbLog.setUserCode(orderin.getUserCode());
								spSaleLogDao.save(tbLog);
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		} else {
			msg.append("未在自营平台查询到该投保单号!");
			saleLog.setResponseData(msg.toString());
			spSaleLogDao.save(saleLog);
		}

		return null;
	}

	@Override
	public String resetState(String state) {
		switch (state) {
		case "0": {
			state = "4"; // 0:新保->0 新保
			break;
		}
		case "2": {
			state = "5"; // 0:下发修改or拒保->0 下发修改or拒保
			break;
		}
		// case "3": {
		// state = "6"; // 0:自动核保->0 自动核保
		// break;
		// }
		case "8": {
			state = "2"; // 8：等待支付->2:未支付
			break;
		}
		case "9": {
			state = "7"; // 8：等待核保->2:等待核保
			break;
		}
		case "4": {
			state = "8"; // 8：等待核保->2:等待核保
			break;
		}
		case "7": {
			state = "9"; // 8：查勘岗->2:查勘岗
			break;
		}
		case "6": {
			state = "10"; // 8：单证审核不通过->2:单证审核不通过
			break;
		}
		case "5": {
			state = "11"; // 8：待单证审核->2:待单证审核
			break;
		}
		case "A": {
			state = "12"; // 8：待绩效审核->2:待绩效审核
			break;
		}
		case "B": {
			state = "13"; // 8：待绩效审核->2:待绩效审核
			break;
		}
		}
		return state;
	}

}
